package com.example.rabbitmqc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author：wlz
 * @Package：com.example.rabbitmqc
 * @Project：redis
 * @name：Consumer
 * @Date：2023/4/10 21:51
 * @Filename：Consumer
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        //3.获取连接Connection
        Connection connection = factory.newConnection();
        //4.创建Channel
        Channel channel = connection.createChannel();
        //5.创建队列
        /*
        queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        1.队列名称
        2.durable是否持久化，当mq重启之后还在
         */
        channel.queueDeclare("hello_world",true,false,false,null);
        //6.发送消息
        /*
        basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)

         */
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            /*
            回调方法，当收到消息后，会自动执行该方法
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println("body:::::"+new String(body));
            }
        };
        channel.basicConsume("hello_world",true,defaultConsumer);


    }
}
